<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class Member extends Model
{
    const GRADE = [
        1=>'大一',
        2=>'大二',
        3=>'大三',
        4=>'大四',
    ];

    const STATUS=[
        1=>'正常',
        -1=>'冻结'
    ];
    public $token_error_msg  = '';
    public $token_error_code = '';

    //登陆(账号密码)
    public function login($username, $password)
    {
        if (empty($username)) {
            exception('请输入您的帐号');
        }

        if (empty($password)) {
            exception('请输入您的密码');
        }

        $member = $this->where(array('username' => $username))->order('uid desc')->find();
        if (!$member) {
            exception('用户不存在');
        }



        if (md5($password) != $member['password']) {
            exception('账号或密码错误');
        }


        //登录信息更新
        $token = $this->autoLogin($member);
        if ($token) {
            $result = [
                'uid'          => $member['uid'],
                'username'       => $member['mobile'],
                'access_token' => $token,
            ];
            return $result;
        }

        return false;
    }


    //用户注册
    public function register($username, $password)
    {


        if (empty($username)) {
            exception('请填写账号');
        }

        if (empty($password)) {
            exception('请输入密码');
        }
        if (strlen($password) < 6 || strlen($password) > 20) {
            exception('密码长度为6-20');
        }

        $is_have = $this->where(array('username' => $username))->find();
        if ($is_have) {
            exception('帐号已存在');
        }

        $data['username']  = $username;
        $data['password']  = md5($password);
        $data['create_time']   = time();
        $data['nickname']   =$this->getRandomString();
        $res   = $this->insertGetId($data);

        if ($res) {

            return true;

        } else {

            return false;
        }

    }

    public function edit_info($data)
    {
        $uid=$this->getAppUid();
        $data['password']=md5($data['password']);
        $res=model("Member")->where(['uid'=>$uid])->update($data);
        if ($res){
            return true;
        }else{

            return false;
        }
    }


    /**
     * 自动登录用户
     */
    public function autoLogin($info)
    {

        if ($token = $this->setLoginUserInfo($info)) {
            return $token;
        }
        return false;
    }

    /**
     * 设置登录信息
     */
    public function setLoginUserInfo($info)
    {

        $token = $this->setUserToken();
        $add = [
            'uid'          => $info['uid'],
            'access_token' => $token,
            'expired_time' => time() + 60 * 60 * 24 * 30,
            'addtime'      => time(),
        ];

        $id = model('MemberToken')->insert($add);
        if (!empty($id)) {
            return $token;
        }
        return false;
    }

    /**
     * 创建用户token
     */
    public function setUserToken()
    {
        $token = md5(uniqid(mt_rand(1, 10000) * mt_rand(1, 10000)));
        return $token;
    }



    //找回密码
    public function find_pwd($mobile, $code, $new_pwd)
    {
        if (empty($mobile)) {
            exception('请输入您的手机号');
        }
        if (!checkmobile($mobile)) {
            exception('手机号格式有误');
        }

        if (empty($code)) {
            exception('请输入短信验证码');
        }

        try {
            $check_code = model('Mobilelog')->check_code($mobile, $code);
        } catch (Exception $e) {
            exception($e->getMessage());
        }

        $user = model("Member")->where(['username' => $mobile])->field('uid')->find();
        if (empty($user)) {
            exception('用户不存在修改失败');
        }

        if (empty($new_pwd)) {
            exception('请填写新密码');
        }

        $password = md5($new_pwd);
        $result   = $this->where(['uid' => $user['uid']])->update(['password' => $password]);
        if ($result) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 获取app登陆用户
     * @return [type] [description]
     */
    public function getAppLoginInfo()
    {
        $uid      = $this->getAppUid();
        $userinfo = model("Member")->where(['uid' => $uid])->find();
        return $userinfo;

    }

    /**
     * 错误信息
     * @param $code 错误码
     * @return string
     */
    public function getAppUid()
    {
        $token =   request()->header('cyaccesstoken');
        $userToken = model("MemberToken")->where(['access_token'=>$token])->find();
        if (!empty($userToken)) {
            return $userToken['uid'];
        }
        return 0;

    }

    public function get_position()
    {
        $userinfo = $this->getAppLoginInfo();

        return $userinfo['is_company']=1 ? $userinfo['position'] : '';
    }

    public static function getToken()
    {
        return request()->header('cyaccesstoken');
    }





    //随机用户名
    function getRandomString($len=6, $chars=null)
    {
        if (is_null($chars)){
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }






}
